# -*- coding: utf-8 -*-

import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from threading import Thread

class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰康祥云二号E款保险产品计划"
    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,66)],
                #性别
                "gender":["M","F"],
                #保额
                "money":["50000","100000","150000","200000","300000","500000"],
                #交费间隔
                "interval":["0"],
                #保障期限
                "expire":["70岁","80岁","90岁"],
                #交费方式
                "payType":["一次交清"],
                #投保对象
                "payObject":["本人/子女/配偶/父母"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["5"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费方式
                "payType": ["年交","月交"],
                # 投保对象
                "payObject": ["本人/子女/配偶/父母"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 55)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["10"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 投保对象
                "payObject": ["本人/子女/配偶/父母"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(0, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["15"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 投保对象
                "payObject": ["本人/子女/配偶/父母"]
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(0, 48)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["20"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 投保对象
                "payObject": ["本人/子女/配偶/父母"]
            }

        }

        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["interval"],plan[k]["expire"],plan[k]["payType"],plan[k]["payObject"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5],v[6]
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5],v[6]
                ))
    #执行爬虫
    def requestJson(self,dt=None,mysql=None):

        data = {
            "codeFlag": "0",
            "productNo": "B43",
            "poltype": "01",
            "responsibility": "B43_1",
            "insuredGender": dt["gender"],
            "birthday": "{0} - 01 - 01".format( str(2020-int(dt["year"]))),
            "applicantGender": dt["gender"],
            "holderBirthday": "{0} - 01 - 01".format( str(2020-int(dt["year"]))),
            "paymentDuration": "1" if dt["interval"] == "0" else dt["interval"],
            "paymentMode": "01" if dt["payType"] == "年交" else "12",
            "insureDuration": ""+dt["expire"].replace("岁","")+"_A",
            "coverageAmount": str(int(int(dt["money"])/10000))
        }

        payload = urlencode( data ).replace("+","")

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "grossFirstPremium" in r.text :
            price = r.json()["grossFirstPremium"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask( data  )
            print("\n/*产品价格数据更新失败:%d*/"%dt["id"])

    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):

        for i in range(5):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()
